package com.ls.fw.web.core.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ls.fw.web.core.servlet.bean.ValidResult;

/**
 * @author Defender
 * 2014年2月21日 下午7:13:33
 */
public abstract class BaseServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
 
	public static final String STATUS_CODE = "status";
	
	public static final String RESULT = "result";
	
	public static final String MSG = "msg";
	
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.handlRequest(SubmitType.GET,request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.handlRequest(SubmitType.POST,request, response);
	}
	
	/**
	 * 获取参数值
	 * @author Defender 
	 * 2014年6月19日下午10:37:28
	 * @param request
	 * @param paramName
	 * @return
	 */
	public String getParameter(HttpServletRequest request,String paramName){
		String value = request.getParameter(paramName);
		if (value == null) {
			return "";
		}
		try {
			return URLDecoder.decode(value,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			return value;
		}
	}
	
	/**
	 * 非法请求
	 * @author Defender
	 * 2014年2月21日 下午7:32:51
	 * @param request
	 * @param response
	 */
	protected abstract void illegalRequest(ValidResult validResult, HttpServletRequest request, HttpServletResponse response, Object... paras);
	
	
	/**
	 * 出现异常
	 * @author Defender
	 * 2014年2月21日 下午7:37:33
	 * @param request
	 * @param response
	 * @param throwable
	 */
	protected abstract void exceptionCaught(HttpServletRequest request, HttpServletResponse response,Object result, Throwable throwable);
	
	
	/**
	 * 处理完请求后执行的回调方法
	 * @author Defender
	 * 2014年2月21日 下午7:40:10
	 * @param req
	 * @param resp
	 */
	protected void callback(HttpServletRequest request, HttpServletResponse response, Object... paras){
	}
	
	
	/**
	 * 处理请求
	 * @author Defender
	 * 2014年2月21日 下午7:41:40
	 * @param submitType
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 * @throws ImageOperateException 
	 */
	protected abstract void handlRequest(SubmitType submitType,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;

	
	/**
	 * 是否为非法请求
	 * @author Defender
	 * 2014年2月21日 下午8:07:22
	 * @param request
	 * @return
	 */
	protected abstract boolean isLegalRequest(HttpServletRequest request);
	
	
	
	
	/**
	 * 设置编码UTF-8:
	 * @author Defender
	 * 2014年2月21日 下午9:22:40
	 * @param req
	 * @param res
	 * @throws UnsupportedEncodingException
	 */
	protected void setEncoding(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
		this.setEncoding(request, response,"UTF-8",null);
	}

	
	/**
	 * 设置编码
	 * @author Defender
	 * 2014年2月21日 下午9:22:32
	 * @param req
	 * @param res
	 * @param encoding
	 * @param type
	 * @throws UnsupportedEncodingException
	 */
	protected void setEncoding(HttpServletRequest request, HttpServletResponse response,final String encoding ,final String type) throws UnsupportedEncodingException{
      String m_encoding = encoding;
      String m_type = type;
      if(isEmpty(m_type)){
    	  m_type = "text/html";
	  } 
      if(isEmpty(m_encoding)){
		  m_encoding = "UTF-8";
	  } 
      request.setCharacterEncoding(m_encoding);
      response.setContentType(m_type+"; charset="+m_encoding);
	}
	
	
	protected boolean isEmpty(String str){
		boolean flag = false;
		if(str==null
		   ||"".equals(str.trim())){
			flag = true;
		}
		return flag;
	}
		
	 /**
     * 发送多个键值对json数据到页面
     * @author Defender
     * 2013-7-1 下午09:13:37
     * @param map
     * @return void
     */
    protected String sendJSONObject(final HttpServletResponse response,final Map<String,Object> map) {  
        JSONObject jsonObj = new JSONObject();
        jsonObj.putAll(map);
        return this.sendJsonData(response,jsonObj);
    } 
    
    
	/**
	 * 发送一个键值对json数据到页面
	 * @author Defender
	 * 2013-7-1 下午09:13:29
	 * @param objName
	 * @param obj
	 * @return void
	 */
    protected String sendJSONObject(final HttpServletResponse response,final String  objName, final Object obj) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(objName, obj); 
       return this.sendJsonData(response,jsonObj);
    }  
    


   /**
    * 发送json数据到页面
    * @author Defender
    * 2013-7-1 下午09:12:17
    * @param jsonObj
    * @return void
    */
    protected String sendJsonData(final HttpServletResponse response, final JSONObject jsonObj){
    	String encoding = "UTF-8";  
        String contentType = "application/json";  
        contentType = contentType + ";charset=" + encoding;  
        response.setContentType(contentType);  
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
        PrintWriter pw = null;
        String msg =jsonObj.toString();
		try {
			pw = response.getWriter();
			pw.write(msg);  
		    pw.flush();   
		} catch (IOException e) {
			this.log("sendJsonData:"+e.getMessage());
		}   
		return msg;
    }
    
    
	/**
	 * 请求类型
	 * @author Defender
	 * 2014年2月21日 下午7:39:30
	 */
	public enum SubmitType{
		 GET
		,POST
	}
}
